<script setup>
import { reactive, ref } from 'vue'
import {useMembersStore} from '@/store/members'
import {useMemberCardStore} from '@/store/memberCard'
import {useCourseStore} from '@/store/course'
import {useMemberCardRelationStore} from '@/store/memberCardRelation'
import {useClassScheduleStore} from '@/store/classSchedule'
import {useReservationRecordStore} from '@/store/reservationRecord'
import { storeToRefs } from 'pinia'
import { ElMessage, ElMessageBox } from 'element-plus'
import CustomTable from '@/components/CustomTable.vue'

const membersStore = useMembersStore()
const {members} = storeToRefs(membersStore)
const memberCardStore = useMemberCardStore()
const memberCardRelationStore = useMemberCardRelationStore()
const courseStore = useCourseStore()
const {courses} = storeToRefs(courseStore)
const classScheduleStore = useClassScheduleStore()
const {classSchedules} = storeToRefs(classScheduleStore)
const reservationRecordStore = useReservationRecordStore()

const curView = ref('courseTable')

const calendar = ref(null)
const day = ref(new Date())

const selectDate = (val) => {
    if (!calendar.value) return
    calendar.value.selectDate(val)
}

//#region 新增排课
const addScheduleDialogVisible = ref(false)

const addScheduleForm = reactive({
    courseId: null,
    teacherName: "",
    classDate: null,
    classTime: null,
})

const showAddSchedulingDialog = () => {
    addScheduleDialogVisible.value = true
}

const addSchedule = () => {
    classScheduleStore.addSchedule(addScheduleForm)
    addScheduleDialogVisible.value = false
    clearAddForm()
}

const clearAddForm = () => {
    addScheduleForm.courseId = null
    addScheduleForm.teacherName = ""
    addScheduleForm.classDate = null
    addScheduleForm.classTime = null
}
//#endregion

//#region 复制排课
const copyScheduleDialogVisible = ref(false)

const copyScheduleForm = reactive({
    fromDate: null,
    toDate: null
})

const showCopySchedulingDialog = () => {
    copyScheduleDialogVisible.value = true
}

const copySchedule = () => {
    classScheduleStore.copySchedule(copyScheduleForm.fromDate, copyScheduleForm.toDate)
    copyScheduleDialogVisible.value = false
    clearCopyForm()
}

const clearCopyForm = () => {
    copyScheduleForm.fromDate = null
    copyScheduleForm.toDate = null
}
//#endregion

//#region 课程页面
let schedule = reactive({})
let course = reactive({})
let memberCardNames = ''
let reservationRecords = []

const reservationRecordColumnData = [
    { prop: "memberName", label: "会员",},
    { prop: "phoneNum", label: "手机号",},
    { prop: "memberCardName", label: "会员卡",},
    { prop: "peopleCount", label: "预约人数",},
    { prop: "consumeTimes", label: "使用次数",},
    { prop: "operationTime", label: "操作时间", width:"200px"},
    { prop: "operator", label: "操作人",},
    { prop: "type", label: "预约结果",},
]

const showCourseView = (scheduleId) => {
    curView.value = 'course'
    schedule = classScheduleStore.getClassScheduleById(scheduleId)
    course = courseStore.getCourseById(schedule.courseId)
    memberCardNames = ''
    course.supportMemberCards.forEach((id) => {
        memberCardNames += `【${memberCardStore.getMemberCardById(id).memberCardName}】`
    })
    reservationRecords = reservationRecordStore.getRecordsByScheduleId(scheduleId)
    console.log(reservationRecords)
}

const showDeleteCourseMessage = () =>{
    ElMessageBox.confirm('注意:若有过会员预约记录，则无法删除此课', '您确定要删除该课程么', {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'warning',
        callback: action => {
            if (action === 'confirm') {
                if (reservationRecordStore.anyReservationRecordByCourseId(schedule.courseId)){
                    ElMessageBox.confirm('该课程有过会员预约记录，无法删除')
                }
                else{
                    classScheduleStore.deleteClassSchedule(schedule.id)
                    ElMessage.success('删除课程成功')
                    curView.value = 'courseTable'
                }
            }
        }
    })
}
//#endregion

//#region 添加预约
const addReservationDialogVisible = ref(false)
let availableMemberCards = []

const addReservationForm = reactive({
    memberId: null,
    memberCardId: null,
    peopleCount: 0,
    remark: "",
})

const showAddReservationDialog = () => {
    addReservationDialogVisible.value = true
}

const getAvailableMemberCards = (memberId) => {
    availableMemberCards = memberCardRelationStore.getMemberCardsByMemberId(memberId)
}

const addReservation = () => {
    reservationRecordStore.addRecord(addReservationForm, schedule.id, course.consumeTimes)
    reservationRecords = reservationRecordStore.getRecordsByScheduleId(schedule.id)
    addReservationDialogVisible.value = false
}
//#endregion

const refresh = ()=>{
    location.reload()
}
</script>

<template>
    <!-- 课程表 -->
    <div v-if="curView==='courseTable'">
        <div>
            <el-button type="primary" @click="showAddSchedulingDialog">新增排课</el-button>
            <el-button type="primary" @click="showCopySchedulingDialog">复制排课</el-button>
            <el-button type="success" @click="refresh">刷新课程表</el-button>
        </div>
        <el-divider/>
        <el-calendar v-model="day" ref="calendar">
            <template #header="{ date }">
                <el-button-group>
                    <el-button @click="selectDate('prev-month')">&lt;</el-button>
                    <el-button @click="selectDate('next-month')">&gt;</el-button>
                </el-button-group>
                <span>{{date}}</span>
                <el-button @click="day=new Date()">今天</el-button>
            </template>
            <template #date-cell="{ data }">
                <el-button v-for="schedule in classSchedules.filter((schedule) => schedule.classDate === data.day)"
                    :key="schedule.id"
                    type="primary"
                    style="height:25px;"
                    @click="showCourseView(schedule.id)">
                    {{schedule.teacherName}}【{{schedule.courseName}}】
                </el-button>
            </template>
        </el-calendar>
    </div>

    <!-- 课程页面 -->
    <div v-if="curView==='course'">
        <div style="display:flex;">
            <div style="margin-left: 20px; width: 120px; color: green;">
                <h3>课程名：</h3>
                <p>开始时间：</p>
                <p>时长：</p>
                <p>限制性别：</p>
                <p>限制年龄：</p>
                <p>支持会员卡：</p>
                <p>上课老师：</p>
            </div>
            <div style="width: 600px">
                <h3>{{schedule.courseName}}</h3>
                <p>{{schedule.classDate + " " + schedule.classTime}}</p>
                <p>{{course.duration}}分钟</p>
                <p>{{course.genderConstraint}}</p>
                <p>{{course.ageConstraint > 0 ? course.ageConstraint + "岁" : "无"}}</p>
                <p>{{memberCardNames}}</p>
                <p>{{schedule.teacherName}}</p>
            </div>
            <div> 
                <el-button type="success" @click="showAddReservationDialog">添加会员预约</el-button>
                <el-button type="danger" @click="showDeleteCourseMessage">删除课程</el-button>
                <el-button type="info" @click="curView = 'courseTable'">返回</el-button>
            </div>
        </div>
        <el-divider/>
        <custom-table
            :tableData="reservationRecords"
            :columnData="reservationRecordColumnData"
        >
        </custom-table>
    </div>

    <!-- 增加排课弹窗 -->
    <el-dialog v-model="addScheduleDialogVisible">
        <el-form :model="addScheduleForm" label-position="right" label-width="100px" style="margin-left: 50px">
            <el-form-item label="课程">
                <el-select v-model="addScheduleForm.courseId" placeholder="请选择课程">
                    <el-option v-for="course in courses" :key="course.id" :label="course.courseName" :value="course.id"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="教师">
                <el-select v-model="addScheduleForm.teacherName" placeholder="请选择老师">
                    <el-option value="张老师"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="日期">
                <el-date-picker v-model="addScheduleForm.classDate" type="date" placeholder="yyyy-mm-dd"></el-date-picker>
            </el-form-item>
            <el-form-item label="上课时间">
                <el-time-select v-model="addScheduleForm.classTime" placeholder="请选择时间"></el-time-select>
            </el-form-item>
            <el-form-item>
                <el-button type="success" @click="addScheduleDialogVisible=false">关闭</el-button>
                <el-button type="success" @click="addSchedule">确定</el-button>
            </el-form-item>
        </el-form>
    </el-dialog>

    <!-- 复制排课弹窗 -->
    <el-dialog v-model="copyScheduleDialogVisible">
        <el-form :model="copyScheduleForm" label-position="right" label-width="100px" style="margin-left: 50px">
            <el-form-item label="将">
                <el-date-picker v-model="copyScheduleForm.fromDate" type="date" placeholder="yyyy-mm-dd"></el-date-picker>
            </el-form-item>
            <el-form-item label="复制到">
                <el-date-picker v-model="copyScheduleForm.toDate" type="date" placeholder="yyyy-mm-dd"></el-date-picker>
            </el-form-item>
            <el-form-item>
                <el-button type="success" @click="copyScheduleDialogVisible=false">关闭</el-button>
                <el-button type="success" @click="copySchedule">确定</el-button>
            </el-form-item>
        </el-form>
    </el-dialog>

    <!-- 添加预约弹窗 -->
    <el-dialog v-model="addReservationDialogVisible" width="600px">
        <el-form :model="addReservationForm" label-position="right" label-width="100px" style="margin-left: 0px">
            <el-form-item label="会员">
                <el-select v-model="addReservationForm.memberId" placeholder="请选择会员" @change="getAvailableMemberCards(addReservationForm.memberId)">
                    <el-option v-for="member in members" :key="member.id" :label="member.memberName" :value="member.id"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="会员卡">
                <el-select v-model="addReservationForm.memberCardId" placeholder="请选择会员卡">
                    <el-option v-for="card in availableMemberCards" :key="card.memberCardId" :label="card.memberCardName" :value="card.memberCardId"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="预约人数">
                <el-input-number v-model="addReservationForm.peopleCount"></el-input-number>
            </el-form-item>
            <el-form-item label="备注">
                <el-input type="textarea" v-model="addReservationForm.remark" placeholder="备注"></el-input>
            </el-form-item>
            <el-form-item>
                <el-button type="success" @click="addReservationDialogVisible=false">关闭</el-button>
                <el-button @click="addReservation">保存</el-button>
            </el-form-item>
        </el-form>
    </el-dialog>
</template>

<style scoped>
p{
    line-height: 10px; /* 或者 line-height: 100%; */
}
</style>
